const { HTTP } = require('../../utils/http');
const { api } = require('../../utils/api');
const { request } = new HTTP();

const app = getApp()

Page({
  data: {
    sex: 1,
    answers: [],
    clearDisable: true,
    id: '',
    title: '',
    lastValue: '',
    value: '',
    editId: ''
  },
  onShow(){
  },
  onLoad(options) {
    this._getAnswer();
    const {id, title, lastValue, editId = ''} = options;
    this.setData({ 
      id, 
      editId,
      title: decodeURIComponent(title), 
      lastValue: decodeURIComponent(lastValue),
      value: decodeURIComponent(lastValue), 
    });
    this.setData({
      clearDisable: this.data.value ? false : true
    });
   
  },
  async _getAnswer() {
    let {returnCode = '', beans = []} = await request({
      url: api.getAnswer,
      method: 'get',
      data: {}
    });
    if (returnCode === '0000') {
      this.setData({
        answers: beans
      });
    }
  },
  bindinputChange(e) {
    this.setData({
      value: e.detail.value
    });
    this.setData({
      clearDisable: this.data.value ? false : true
    });
  },
  clearText() {
    this.setData({value: ''});
  },
  sure() {
    if (!this.data.value) {
      wx.showToast({
        title: '内容不能为空',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    this._update();
  },
  async _update() {
    let params = {
      content: this.data.value,
      question_id: this.data.id
    };
    if (!this.data.editId) params.title = this.data.title; 
    if (this.data.editId) params.id = this.data.editId;

    const { returnCode = null, bean = {} } = await request({
      url: this.data.editId ? api.userQuestionUpdate : api.userQuestionAdd,
      method: 'post',
      data: params
    });
    if (returnCode === '0000') {
      wx.hideLoading();
      wx.navigateBack({
        delta: 1
      });
    }
  }
})
